package com.fu.jdbc05.handler;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;

/**
 * @author 付大大
 * @description
 * @create 2021-01-31 19:31
 */
public class BeanHandler<T> implements ResultSetHandler<T> {

    private Class<T> beanClass;


    public BeanHandler(Class<T> beanClass) {
        this.beanClass = beanClass;
    }

    @Override

    public T handler(ResultSet resultSet) {
        T bean = null;
        try {
            bean = beanClass.newInstance();
            if (resultSet.next()) {
                ResultSetMetaData metaData = resultSet.getMetaData();
                int columnCount = metaData.getColumnCount();
                for (int i = 1; i <= columnCount; i++) {
                    String columnName = metaData.getColumnName(i);
                    Object object = resultSet.getObject(columnName);
                    //拿到set get方法
                    PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName.toLowerCase(), beanClass);
                    Method writeMethod = propertyDescriptor.getWriteMethod();
                    writeMethod.invoke(bean, object);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bean;
    }

}
